#include "dbdebug.h"
#include <QSqlQuery>
#include <QCoreApplication>
//#include <QMutex>
//#include <QMutexLocker>

using namespace Rt;
QString DbDebug::mTable = QString();
QSqlDatabase DbDebug::mDb = QSqlDatabase();

DbDebug::DbDebug(const QSqlDatabase &db, const QString &logTable)
{
    //DbDebug::mMsgHandler = this;
    DbDebug::mDb = db;
    DbDebug::mTable = logTable;
}

void DbDebug::messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
//    static QMutex mutex;
//    QMutexLocker locaker(&mutex);
    Q_UNUSED(context)
    int ntype = 0;
    switch(type) {
    case QtDebugMsg: ntype = 0; break;
    case QtWarningMsg: ntype = 1; break;
    case QtCriticalMsg: ntype = 2; break;
    case QtFatalMsg: ntype = 3;
        //abort();
    }
    QSqlQuery q(DbDebug::mDb);
    q.exec(QString("INSERT INTO `%1` (`type`,`msg`,`dt`) VALUES ('%2', '%3', NOW());")
           .arg(DbDebug::mTable).arg(ntype).arg(msg));
}


